package io.netty.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private Charset charset;

    public NettyServerHandler() {
        charset = Charset.forName("UTF-8");
    }

    /**
     * 当客户端发送数据到通道，这里是通道读取
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(Thread.currentThread().getName() + " 接受请求");
        ByteBuf buf = (ByteBuf) msg;

        System.out.println("服务端接受到的数据:" + buf.toString(charset));
    }

    /**
     * 通道数据读取完毕调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端数据读取完毕");
        ByteBuf buf = Unpooled.copiedBuffer("hello client", charset);
        ctx.writeAndFlush(buf);
    }

    /**
     * 当客户端建立了连接过后，服务端会调用channelActive方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道激活");
        //建立连接可以给客户端发送消息
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello", charset));

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("11111");
    }

    /**
     * 当客户端建立了连接过后，要注册到通道上会调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注册...");
    }

    /**
     * 当客户端失去连接过后，会调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端通道移除");
    }

    /**
     * 出现异常调用
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("出现异常");
    }
}